<?php
/**
 * @file utilm.php
 * @synopsis  其他功能
 * @author Yee, <rlk002@gmail.com>
 * @version 1.0
 * @date 2014-10-13 10:20:40
 */


class Utilm extends CI_Model
{
    function __construct()
    {
        // 初始化并继承cache
        parent::__construct();
    }

    /**
     * 获取验证码 验证码文件存储在 项目目录/data/caches 验证码失效查看该文件
     * @param string $phonenumber
     * @param int $num
     * @param $prefix
     * @param int $expiration_time
     * @return string
     */
    public function get_yanzheng_code($phonenumber = '',$num = 4,$prefix,$expiration_time = 1200)
    {
        $cache = $this->redis;
        $existcode = $cache->get($prefix . md5($phonenumber));
        if($existcode)
        {
            return $existcode;
        }
        $code = random($num,1);
        $cache->save($prefix . md5($phonenumber),$code,$expiration_time);
        return $code;
    }

    public function v_yanzheng_code($phonenumber = '',$usercode,$prefix = 'yanzheng')
    {
        $cache = $this->redis;
        $code = $cache->get($prefix . md5($phonenumber));
        if(!$code)
        {
            return '1';
        }
        return $usercode == $code ? '2': '3';
    }

    /*//备份线路
    public function sendyanzheng($cache,$phonenumber,$prefix = 'yanzheng')
    {
        $code = $this->get_yanzheng_code($cache,$phonenumber,$num = 4,$prefix);
        $this->load->library('curl');
        $ret = $this->curl->simple_post('http://qyapi.medical-lighter.com/sms/sendyzmsms.json',array('cellphone' => $phonenumber,'smstext' => "【轻盈医学】您注册轻盈医学的手机验证码为：%P%,该验证码%P%分钟里有效。",'code' => $code,'vtime' => '5'));
        $ret = json_decode($ret,1);
        return $ret;
    }*/


    //一客一签线路
    public function sendyanzheng($phonenumber,$prefix = 'yanzheng')
    {
        $cache = $this->redis;
        //
        //企业ID $userid
        $userid = '';
        //用户账号 $account
        $account = 'ADC0072';
        //用户密码 $password
        $password = 'ADC007285';
        //发送到的目标手机号码 $mobile
        $mobile = $phonenumber;
        //短信内容 $content
        $code = $this->get_yanzheng_code($phonenumber,$num = 4,$prefix);
        $vtime = 5;
        //$content = "【轻盈医学】您注册轻盈医学的手机验证码为：".$code.",该验证码".$vtime."分钟内有效。";
        $content = "【轻盈医学】验证码".$code."，5分钟内有效。";



        //发送短信（其他方法相同）
        $gateway = "http://114.113.154.13/sms.aspx?action=send&userid={$userid}&account={$account}&password={$password}&mobile={$mobile}&content={$content}&sendTime=&extno=";
        $result = file_get_contents($gateway);
        $xml = simplexml_load_string($result);


        //写入日志
        $timestamp = time();
        $logtime = date('Y-m-d H:i:s',$timestamp);
        $f = date('Ymd',$timestamp);
        $filename = BASEDIRS . 'data/logs/cellphonelogs/client.phone.log.'.$f;

        $record = "$logtime    $phonenumber     $code   ".json_encode($xml)."   $this->pid    $this->softversion   $this->uid  \n";
        writelog($filename, $record, 'ab');

        //转换成数组
        $ret = json_decode( json_encode( $xml),true);
        $res = array();
        $res['returnstatus'] = $ret['returnstatus'];
        $res['message']      = $ret['message'];
        if($ret['returnstatus']=='Success')
        {
            $res['code']         = 1;
        }else{
            $res['code']     = -1;
        }
        //$ret = array("returnstatus">$xml->returnstatus,"message"=>$xml->message);
        return $res;
        //echo "返回状态为：".$xml->returnstatus."<br>";
        //echo "返回信息：".$xml->message."<br>";
        //echo "返回余额：".$xml->remainpoint."<br>";
        //echo "返回本次任务ID：".$xml->taskID."<br>";
        //echo "返回成功短信数：".$xml->successCounts."<br>";
        //echo "<br>";
        //echo "<br>";
    }


    public function sendyanzheng_voice($phonenumber,$prefix = 'yanzheng')
    {
        //
        //企业ID $userid
        $userid = '';
        //用户账号 $account
        $account = 'y0037';
        //用户密码 $password
        $password = 'QingYing%5';
        //发送到的目标手机号码 $mobile
        $mobile = $phonenumber;
        //短信内容 $content
        $code = $this->get_yanzheng_code($phonenumber,$num = 4,$prefix);
        $vtime = 5;
        //$content = "【轻盈医学】您注册轻盈医学的手机验证码为：".$code.",该验证码".$vtime."分钟内有效。";
        $content = "【轻盈医学】验证码".$code."，5分钟内有效。";



        //发送短信（其他方法相同）
        $gateway = "http://111.206.219.17/c-pt/pt/interface.php?username=$account&password=$password&action=captcha&called=$phonenumber&callid=01062507494&captcha=$code";
        $result = file_get_contents($gateway);
        $xml = simplexml_load_string($result);


        //写入日志
        $timestamp = time();
        $logtime = date('Y-m-d H:i:s',$timestamp);
        $f = date('Ymd',$timestamp);
        $filename = BASEDIRS . 'data/logs/cellphonelogs/client.phone.log.'.$f;

        $record = "voice $logtime    $phonenumber     $code   ".json_encode($xml)."   $this->pid $this->softversion   $this->uid  \n";
        writelog($filename, $record, 'ab');


        $ret = json_decode( json_encode( $xml),true);
        return $ret;
        //echo "返回状态为：".$xml->returnstatus."<br>";
        //echo "返回信息：".$xml->message."<br>";
        //echo "返回余额：".$xml->remainpoint."<br>";
        //echo "返回本次任务ID：".$xml->taskID."<br>";
        //echo "返回成功短信数：".$xml->successCounts."<br>";
        //echo "<br>";
        //echo "<br>";
    }

    public function del_yanzheng_cache($phonenumber) {
        $this->redis->delete('yanzheng' . md5($phonenumber));
    }
    //统一发送短信验证码
    public function send_sms($phonenumber,$prefix = 'yanzheng')
    {

        $cache   = $this->redis;
        $type    = $cache->get(SMS_TYPE);
        $ip      = getip_out();
        $ip_key  = SMS_IP_LOCK.$ip;
        if($cache->get($ip_key))
        {
           $cache->save($ip_key,$cache->get($ip_key)+1,SMS_IP_LOCK_EXPIRE_TIME);
        }else{
            $cache->save($ip_key,1,SMS_IP_LOCK_EXPIRE_TIME);
        }

        $phone_key = SMS_PHONE_LOCK.$phonenumber;
        $cache->save($phone_key,1,SMS_PHONE_EXPIRE_TIME);
        if($type == 1)
        {
            $res =   $this->sendyanzheng($phonenumber,$prefix);
        }else{
            $res =   $this->send_ym_sms($phonenumber,$prefix);
        }
        return $res;
    }
    //统一发送语音验证码
    public function send_voice_sms($phonenumber,$prefix = 'yanzheng')
    {
        $cache = $this->redis;
        $type  = $cache->get(SMS_TYPE);
        if($type == 1)
        {
            $res =   $this->sendyanzheng_voice($phonenumber,$prefix);
        }else{
            $res =   $this->send_ym_voice($phonenumber,$prefix);
        }
        return $res;
    }
    //亿美发送短信验证码 8SDK-EMY-6699-RGTLS，密码077546，特服号982875
    public function send_ym_sms($phonenumber,$prefix = 'yanzheng')
    {
        $code = $this->get_yanzheng_code($phonenumber,$num = 4,$prefix);
        $content = "验证码".$code."，5分钟内有效。";

        return $this->sendSMS($phonenumber, $content);
    }
    //亿美发送语音验证码
    public function send_ym_voice($phonenumber,$prefix = 'yanzheng')
    {
        $code = $this->get_yanzheng_code($phonenumber,$num = 4,$prefix);
        $this->load->model('Voice_codem');
        $ret = $this->Voice_codem->sendVoice($phonenumber,$code);
        //写入日志
        $timestamp = time();
        $logtime = date('Y-m-d H:i:s',$timestamp);
        $f = date('Ymd',$timestamp);
        $filename = BASEDIRS . 'data/logs/cellphonelogs/client.phone.log.'.$f;

        $record = "voice $logtime    $phonenumber     $code   ".$ret."   $this->pid $this->softversion   $this->uid  \n";
        writelog($filename, $record, 'ab');
        $res = strstr($ret,'-');
        if($res)
        {
            $return = array('code'=>'-1','tip'=>'验证码发送失败,请稍后再试');
        }else{
            $return = array('code'=>'1' ,'tip'=>'验证码发送成功');
        }
        return $return;

    }
    //更新短信渠道
    public function save_sms_cache($type)
    {
        $cache    =  $this->redis;
        $cache->save(SMS_TYPE,$type,0);
        $type     =  $cache->get(SMS_TYPE);
        return $type;
    }


    /**
     *
     * @param $phone_number
     * @param $content
     * @return array
     */
    public function sendSMS($phone_number, $content)
    {
        $url   = "http://hprpt2.eucp.b2m.cn:8080/sdkproxy/sendsms.action";
        $param = array();
        $param['cdkey']     = '8SDK-EMY-6699-RGTLS';
        $param['password']  = '077546';
        $param['message']   =  "【轻盈医学】" . $content;
        $param['addserial'] = '';
        $param['phone']     = $phone_number;
        $res = curl($url,$param);
        $res =  trim($res, "\r\n");
        $xml = simplexml_load_string($res);
        $str  = "发送人手机号".$param['phone']."返回值".$xml->error;
        //写入日志
        $timestamp = time();
        $logtime = date('Y-m-d H:i:s',$timestamp);
        $f = date('Ymd',$timestamp);
        $filename = BASEDIRS . 'data/logs/cellphonelogs/client.phone.log.'.$f;

        $record = "$logtime    $phone_number     $content   ".json_encode($xml)."   $this->pid    $this->softversion   $this->uid  \n";
        writelog($filename, $record, 'ab');
        $res = array(
            'code' => (string)$xml->error,
            'message' => (string)$xml->message,
            'returnstatus' => "Faild",
        );
        if($xml->error == 0) {
            $res['code'] = 1;
            $res['returnstatus'] = "Success";
        }
        return $res;
    }

    /**
     * 每个ip一天最多100次
     * @param $ip
     * @return int|mixed
     */
    public function get_ip_lock($ip)
    {
        $key = SMS_IP_LOCK.$ip;
        $res = $this->redis->get($key);
        if(!$res)
        {
            return 0;
        }elseif($ip=='127.0.0.1')
        {
            return 0;
        }
        return $res;
    }
    /**
     * 每个手机每分钟只能发一次
     */
    public function get_phone_lock($phone)
    {
        $key = SMS_PHONE_LOCK.$phone;
        $res = $this->redis->get($key);
        if(!$res)
        {
            return 0;
        }
        return $res;
    }
}
